package cn.edu.nks.dormitory.login.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import cn.edu.nks.dormitory.login.db.IDBService;
import cn.edu.nks.dormitory.login.dbimpl.DBService;
import cn.edu.nks.dormitory.model.UserInfo;
import cn.edu.nks.util.DateTimeUtil;
import cn.edu.nks.util.MD5Utile;

/**
 * 用户登录
 * @author wangbs
 *
 */
public class LoginAction extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(LoginAction.class);
	
	private IDBService idbService = new DBService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/jsons;charset=utf-8");
		
		String userName = req.getParameter("userName");
		String passWord = MD5Utile.getMD5(req.getParameter("passWord"));
		logger.warn(String.format("user %s login this ms time %s", userName,DateTimeUtil.toDateString(new Date())));
		
		UserInfo currentUser = idbService.selectUserByUnameAndPsw(userName, passWord);
		JSONObject obj = new JSONObject();
		if(currentUser != null){
			obj.put("code", "succ");
			obj.put("currentUser", JSONObject.fromObject(currentUser).toString());
			HttpSession session = req.getSession();
			session.setAttribute("currentUser", currentUser);
		}else{
			obj.put("code", "fail");
		}
		PrintWriter out = resp.getWriter();
		out.write(obj.toString());
	}
}
